
import React, { Component, Fragment } from 'react';
import { inject, observer } from 'mobx-react';
import { WeaDialog, WeaSearchGroup, WeaFormItem, WeaUpload, WeaLocaleProvider, WeaTools, WeaTab, WeaAlertPage } from 'ecCom';
import { WeaSwitch } from 'comsMobx';
import { Button, Row, Col } from 'antd';
import { toJS } from 'mobx';

const { getLabel } = WeaLocaleProvider;

@inject('registDocStore')
@observer
class ReceiveRegistDialog extends Component {
  componentDidMount() {
    this.props.registDocStore.getBaseInfoForDemo();
  }

  render() {
    const { registDocStore } = this.props;
    const { eleRegistShow, eleRegistShowOnCancel, createWorkflowDialog, createWorkflowOnCancel } = registDocStore;
    return (
      <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@7flxh0`}>
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@vp52ht`}
          title={getLabel(500190, '来文智能登记')}
          visible={eleRegistShow}
          icon={'icon-coms-official'}
          iconBgcolor={'#F14A2D'}
          onCancel={eleRegistShowOnCancel}
          buttons={this.getDialogBtn()}
          style={{ width: '90%', height: '600px' }}
          className="doc-receiveRigist-smartRegist"
        >
          {this.eleRegist()}
        </WeaDialog>

        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@4i6ms6`}
          title={getLabel(500190, '创建流程')}
          visible={createWorkflowDialog}
          icon={'icon-coms-official'}
          iconBgcolor={'#F14A2D'}
          onCancel={() => createWorkflowOnCancel({ cancel: true })}
          style={{ width: '65%', height: '600px' }}
          className="doc-receiveRigist-smartRegist"
        >
          {this.getCreatWorkflowDailog()}
        </WeaDialog>

      </Fragment>
    );
  }

  getCommonDialog() {
    const { registProcessShow, type, secondDialogOncCancel } = this.props.registDocStore;
    let title = getLabel(500086, '登记处理');
    let btn = this.getRegistProcessBtn();
    if (type == '1') {
      title = getLabel(500190, '收文智能登记');
    } else if (type == '2') {
      title = getLabel(500278, '二维码扫码登记');
    }
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@frljqh`}
        title={title}
        visible={registProcessShow}
        icon={'icon-coms-official'}
        iconBgcolor={'#F14A2D'}
        onCancel={() => secondDialogOncCancel()}
        buttons={btn}
        style={{ width: '80%' }}
        className="odoc-receiveDialog-secondDialog"
      >
        {this.registProcessContent()}
      </WeaDialog>
    );
  }

  // 智能登记按钮
  getDialogBtn() {
    const { smartRegistration, loading, fileInfoArr, registDailogKey, step, nextTept, eleRegistShowOnCancel } = this.props.registDocStore;
    const disabled = !(toJS(fileInfoArr.Document_Text).length > 0);
    let btns = [];
    if (step == '1') {
      if (registDailogKey == '3') {
        btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nyevc2@sign`} type={'primary'} onClick={() => nextTept()} disabled={disabled || loading}> {getLabel(500086, '登记处理')}</Button>);
      }
      if (registDailogKey == '0' || registDailogKey == '1') {
        btns.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@swgvfv@next`} type={'primary'} onClick={() => smartRegistration()} disabled={disabled || loading}>{getLabel(1402, '下一步')}</Button>,
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wc6y67@clean`} type={'primary'} onClick={() => this.clear()} > {getLabel(311, '清除')}</Button>,
        );
      }
      btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gyl8se@cancel`} type={'primary'} onClick={() => eleRegistShowOnCancel()}>{getLabel(31129, '取消')}</Button>);
    } else if (step == '2') {
      btns = this.getRegistProcessBtn();
    }
    if (registDailogKey == '2') {
      btns = this.getRegistProcessBtn();
    }
    return btns;
  }

  // 清除方法
  clear() {
    const { registDocStore } = this.props;
    this.refs.uploadText.setState({ listT: [] });
    registDocStore.setMobxState({ fileId: {}, fileInfoArr: { Document_Attachments: [], Document_Text: [] } });
  }

  getSmartRegistDialog() {
    const { setFileInfo, fileInfoArr } = this.props.registDocStore;
    const DocumentTextValue = toJS(fileInfoArr.Document_Text)[0] && toJS(fileInfoArr.Document_Text)[0].filename || '';
    let DocumentAttachmentsValue = '';
    toJS(fileInfoArr.Document_Attachments).forEach((element) => {
      DocumentAttachmentsValue += `${element.filename} `;
    });
    return (
      <div className="dialogContent">
        <img src="/images/ecology9/odoc/smartRegistIcon.png" style={{ width: 74, height: 74 }} />
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@tgndj6`} className="Document_Attachments">
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@n3qx1y`} span={10} offset={7}>
            <input type="text" ref="Document_Text" id="Document_Text" value={DocumentTextValue} disabled={true} placeholder={getLabel('384197', '请上传文件')} />
            <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@7semcs`}
              uploadUrl="/api/doc/upload/uploadFile"
              category="string"
              onChange={(ids, list) => setFileInfo('Document_Text', ids, list, 'smartRegist')}
              ref="uploadText"
              limitType="pdf,doc,docx"// 正文上传文件的类型
              maxFilesNumber={1}
            >
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lb6rsv`} type="primary">{getLabel(500085, '上传正文')}</Button>
            </WeaUpload>
          </Col>
        </Row>
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@7zcisi`} className="Document_Attachments">
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@onqjim`} span={10} offset={7}>
            <input type="text" id="Document_Attachments" disabled={true} value={DocumentAttachmentsValue} placeholder={getLabel('384197', '请上传文件')} ref="Document_Attachments" />
            <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@o4h5qe`}
              uploadUrl="/api/doc/upload/uploadFile"
              category="string"
              onChange={(ids, list) => setFileInfo('Document_Attachments', ids, list, 'smartRegist')}
              ref="uploadAttachments"
              datas={toJS(fileInfoArr.Document_Attachments)}
              showClearAll={true}
            >
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vg7fi3`} type="primary">{getLabel(128095, '上传附件')}</Button>
            </WeaUpload>
          </Col>
        </Row>
      </div>
    );
  }

  handworkDialogChildren() {
    const { registDocStore } = this.props;
    const { handworkForm, handwordCondition, registDailogKey } = registDocStore;
    const { isFormInit } = handworkForm;
    let group = [];
    isFormInit && toJS(handwordCondition).map((c, index) => {
      let items = [];
      c.items.map((field) => {
        let comChild = {};
        if (field.conditionType.toUpperCase() == WeaTools.types.UPLOAD && field.domkey[0] == 'Document_Text') {
          comChild = (<WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@ubjofc@${field.domkey[0]}`}
            uploadUrl="/api/doc/upload/uploadFile"
            category="string"
            maxUploadSize={5}
            listType="list"
            maxFilesNumber={1}
            multiSelection={false}
            viewAttr={field.viewAttr}
            limitType="pdf,doc,docx,jpg,png,gif"// 正文上传文件的类型
            onChange={(ids, list) => registDocStore.setFileInfo('Document_Text', ids, list)}
            clearWhenReset={false}
            showClearAll={false}
            datas={toJS(registDocStore.fileInfoArr.Document_Text) || []}
          />);
        } else if (field.conditionType.toUpperCase() == WeaTools.types.UPLOAD && field.domkey[0] == 'Document_Attachments') {
          comChild = (<WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@atmsgy@${field.domkey[0]}`}
            uploadUrl="/api/doc/upload/uploadFile"
            category="string"
            maxUploadSize={5}
            listType="list"
            multiSelection={true}
            viewAttr={field.viewAttr}
            onChange={(ids, list) => registDocStore.setFileInfo('Document_Attachments', ids, list)}
            clearWhenReset={false}
            showClearAll={false}
            datas={toJS(registDocStore.fileInfoArr.Document_Attachments) || []}
          />);
        } else if (field.conditionType.toUpperCase() == WeaTools.types.BROWSER) {
          comChild = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@8sf8or@${field.domkey[0]}`} fieldConfig={field} form={handworkForm} />;
        } else {
          comChild = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@5ttthj@${field.domkey[0]}`} fieldConfig={field} form={handworkForm} />;
        }

        if ((registDailogKey == '0' || registDailogKey == '1' || registDailogKey == '2' && field.conditionType.toUpperCase() == WeaTools.types.UPLOAD) && (field.domkey[0] == 'Document_Text' || field.domkey[0] == 'Document_Attachments')) {

        } else if (field.domkey[0] == 'Document_Text' || field.domkey[0] == 'Issued_Number_of_Document' || field.domkey[0] == 'Main_Receiver_Department' || field.domkey[0] == 'Copy_to_Department') {
          items.push({
            com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@zcslli@${field.domkey[0]}`}
              hasBorder={true}
              label={`${field.label}`}
              labelCol={{ span: '6' }}
              error={handworkForm.getError(field)}
              tipPosition="bottom"
              wrapperCol={{ span: '18' }}
            >
              {comChild}
            </WeaFormItem>),
            col: field.colSpan,
            hide: handworkForm.isHide(field, () => false),
          });
        } else {
          items.push({
            com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@au5qz8@${field.domkey[0]}`}
              hasBorder={true}
              label={`${field.label}`}
              labelCol={{ span: '6' }}
              error={handworkForm.getError(field)}
              tipPosition="bottom"
              wrapperCol={{ span: '18' }}
            >
              {comChild}
            </WeaFormItem>),
            col: field.colSpan,
            hide: handworkForm.isHide(field, () => false),
          });
        }
      });
      if (registDailogKey == '0' || registDailogKey == '1' || registDailogKey == '2') {
        if (index == 0) {
          group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@szr7aj@${index}`} needTigger={false} title={''} showGroup={c.defaultshow} items={items} className="handworkRegist" />);
        } else {
          group.unshift(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@3uvnsj@${index}`} needTigger={false} title={''} showGroup={c.defaultshow} items={items} className="handworkRegist" />);
        }
      } else {
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@hkpclg@${index}`} needTigger={false} title={''} showGroup={c.defaultshow} items={items} className="handworkRegist" />);
      }
    });
    return group;
  }

  // 二级弹窗
  registProcessContent() {
    const { type } = this.props.registDocStore;
    return (
      <div className="odoc_registProcessDialog">
        <div className="registProcess-left">
          {type == '0' && this.registProcess()}
          {type == '1' && this.registProcess()}
          {type == '2' && <div className="sweepCodeContent">{this.sweepCodeRegist()}</div>}
          {type == '3' && this.registProcess()}
        </div>
        <div className="registProcess-right">
          {this.handworkDialogChildren()}
        </div>
        <div className="clearFloat" />
      </div>
    );
  }

  // 收文登记弹窗按钮
  getRegistProcessBtn() {
    const { loading, registSave, previousTept, selectRowId, isReceivecheck, registDailogKey, eleRegistShowOnCancel } = this.props.registDocStore;
    const isShow = !(toJS(selectRowId).length > 0);
    let btns = [];
    if (isReceivecheck) {
      btns = [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bmn0y8@ok`} type={'primary'} onClick={() => eleRegistShowOnCancel()} disabled={loading}>{getLabel(500111, '确定')}</Button>,
      ];
    } else {
      btns = [
        (registDailogKey == '0' || registDailogKey == '1' || registDailogKey == '3') && isShow && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5gdl7r@prev`} type={'primary'} onClick={() => previousTept()}>{getLabel(1876, '上一步')}</Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vo8iy2@dispose`} type={'primary'} onClick={() => registSave(true)} disabled={loading}>{getLabel('', '收文处理')}</Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@j6ia4g@save`} type={'primary'} onClick={registSave} disabled={loading}>{getLabel(500114, '登记保存')}</Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qim3lt@cancel`} type={'primary'} onClick={() => eleRegistShowOnCancel()}>{getLabel(31129, '取消')}</Button>,
      ];
    }
    return btns;
  }

  registProcess() {
    const { fileId, fileInfoArr, docId } = this.props.registDocStore;
    let pdfId = '';
    if (toJS(fileInfoArr.Document_Text)[0] && toJS(fileInfoArr.Document_Text)[0].fileExtendName == 'pdf' && fileId.Document_Text) {
      pdfId = fileId.Document_Text;
    } else {
      pdfId = docId;
    }
    const src = `/docs/pdfview/web/pdfViewer.jsp?canPrint=false&canDownload=false&pdfimagefileid=${pdfId}`;
    return (
      <iframe src={src} width="100%" height="100%" frameBorder="0" title="iframe" />
    );
  }

  sweepCodeRegist() {
    const { registDocStore } = this.props;
    return (
      <div className="doc-receiveRigist-smartRegist">
        <div className="dialogContent">
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@log6iq`} className="sweepCodeUpload">
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@3vd297`}>
              {/* <span className="sweepCode">二维码</span> */}
              <input type="text" id="sweepCode" disabled={true} placeholder={getLabel('384197', '请上传文件')} ref="sweepCode" />
              <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@51yhah`}
                uploadUrl="/api/doc/upload/uploadFile"
                category="string"
                onChange={(ids, list) => registDocStore.setFileInfo('sweepCode', ids, list, 'smartRegist')}
                ref="uploadAttachments"
              >
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@dl0zlc`} type="primary">{getLabel('500369', '上传二维码')}</Button>
              </WeaUpload>
            </Col>
          </Row>
        </div>
      </div>
    );
  }

  eleRegist() {
    const { registDocStore } = this.props;
    const { registDailogKey, changeTab, step, isShowAllTab } = registDocStore;
    let tabData = [
      {
        color: '#fea468',
        groupid: 'flowRes',
        showcount: true,
        title: getLabel('501799', '扫码登记'),
        viewcondition: 2,
      },
      {
        color: '#9766fd',
        groupid: 'flowOver',
        showcount: true,
        title: getLabel('391004', '手工登记'),
        viewcondition: 3,
      },
    ];
    isShowAllTab && tabData.push({
      groupid: 'flowRes',
      title: getLabel('504656', '电子登记'),
      viewcondition: 0,
    },
      {
        groupid: 'flowRes',
        title: getLabel('504657', '拍照登记'),
        viewcondition: 1,
      });

    return (
      <div className="">

        {
          step == '1' &&
          <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@yzbyvj`}
            datas={tabData}
            keyParam="viewcondition" // 主键
            countParam="groupid" // 数量
            selectedKey={registDailogKey}
            onChange={v => changeTab(v)}
          />
        }

        {
          step == '1' &&
          <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@1x7zn8`}>
            {registDailogKey == '0' && this.getSmartRegistDialog()}
            {registDailogKey == '1' && this.getPhotoRegist()}
            {registDailogKey == '3' && this.handworkDialogChildren()}
          </Fragment>
        }

        {
          step == '2' &&
          <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@ycgplr`}>
            {(registDailogKey == '0' || registDailogKey == '1') && this.registProcessContent()}
            {registDailogKey == '3' && this.registProcessContent()}
          </Fragment>
        }

        {registDailogKey == '2' && this.registProcessContent()}
      </div>
    );
  }

  getPhotoRegist() {
    const { setFileInfo, fileInfoArr } = this.props.registDocStore;
    let nameArr = [];
    if (toJS(fileInfoArr.Document_Text) && toJS(fileInfoArr.Document_Text).length > 0) {
      toJS(fileInfoArr.Document_Text).map((item) => {
        nameArr.push(`<p class="photoFileNameList" title="${item.filename}">${item.filename}</p>`);
      });
    }
    const photoName = nameArr.join('');
    return (
      <div className="doc-receiveRigist-smartRegist">
        <div className="dialogContent">
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@1snwou`} className="Document_Attachments">
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@67l0fb`} span={10} offset={7}>
              {
                photoName == '' &&
                <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@4l26h0`} icon={'icon-coms-blank'}>
                  <div style={{ color: '#000' }}> {getLabel('517306', '没有上传任何文件')} </div>
                </WeaAlertPage>
              }

              {photoName != '' &&
                <div className="photoNameBox">
                  <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@6dfp4e`}>
                    <div className="box-title">{getLabel('517307', '已上传文件')}</div>
                    <div className="box-content" ref={ref => this.photoValue = ref} dangerouslySetInnerHTML={{ __html: photoName }} />
                  </Fragment>
                </div>
              }

              <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@j4i5wt`}
                uploadUrl="/api/doc/upload/uploadFile"
                category="string"
                onChange={(ids, list) => setFileInfo('Document_Text', ids, list, 'smartRegist')}
                ref="uploadText"
                limitType="jpg,png,gif"// 正文上传文件的类型
              // maxFilesNumber={1}
              >
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@76h1vx`} type="primary">{getLabel(500085, '上传图片')}</Button>
              </WeaUpload>
            </Col>
          </Row>
        </div>
      </div>
    );
  }


  getCreatWorkflowDailog() {
    const { tabs, workflowKeys, changeWorkflowTab } = this.props.registDocStore;
    return (
      <div>
        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@orm7pu`}
          datas={tabs}
          keyParam="viewcondition" // 主键
          countParam="groupid" // 数量
          selectedKey={workflowKeys}
          onChange={changeWorkflowTab}
        />
        <div className="odoc_wolkflowList">{this.getWorkflowBox()}</div>
      </div>
    );
  }

  getWorkflowBox() {
    const { registDocStore } = this.props;
    const { workflowData } = registDocStore;
    return (
      toJS(workflowData).map(item => (
        <div className="workflowItem" key={item.workflowid} onClick={() => registDocStore.openCreatFlowWindow(item.workflowid, item.workflowname)}>
          <a className="flowWorkName">{item.workflowname}</a>
          <div className="addButton">+</div>
        </div>
      ))
    );
  }
}

export default ReceiveRegistDialog;

